<template>
  <view class="login-card feat-grid">

    <view @click="isLoginType = !isLoginType" class="login-card-head fx-row-c main-bg"
          :style="{'background-image': 'url('+ ossImage('login/logo.png')+')'}"
    >
    </view>

    <view class="login-card-desc">店家端</view>

    <view class="login-card-box">
      <!--一键登录-->
      <view v-if="isLoginType" class="login-card-box-a">
        <view>
          <input disabled class="login-phone" type="number" placeholder="" value="" />
        </view>
        <button v-if="isChecked" class="login-btn-a mt30"
                type="default"
                open-type="getPhoneNumber"
                :loading="subBtnLoading"
                @getphonenumber="handleGetphonenumber"
        >
          手机号快捷登录
        </button>
        <button v-else class="login-btn-a mt30"
                type="default"
                @click="agreementPrompt"
        >
          手机号快捷登录
        </button>
        <button class="login-btn-b mt30"
                type="default"
                @click="changeLoginType"
        >
          输入手机号登录/注册
        </button>
      </view>

      <!--验证码登录-->
      <view v-else class="login-card-box-b">
        <view class="login-card-box-b-list">
          <uv-input
            placeholder-style="color:#ccc;font-weight:400"
            class="login-input"
            maxlength="20"
            placeholder="请您输入手机号"
            v-model="formData.phone"
            type="number"
            height="80" auto-height="autoHeight"
          >
            <template #header>
              <view class="login-input-icon"><uv-icon size="36" name="phone"></uv-icon></view>
            </template>
          </uv-input>
        </view>
        <view class="login-card-box-b-list">
          <uv-input
            placeholder-style="color:#ccc;font-weight:400"
            class="login-input"
            maxlength="20"
            placeholder="请您输入验证码"
            v-model="formData.code"
            type="text"
            height="80" auto-height="autoHeight"
          >
            <template #header>
              <view class="login-input-icon"><uv-icon size="40" name="custom-icon-anquan1" custom-prefix="custom-icon"></uv-icon></view>
            </template>
            <template #suffix>
              <text @click="handleSend" class="login-input-icon login-code">{{tips}}</text>
            </template>
          </uv-input>
        </view>
        <uv-verification-code
          :seconds="60"
          change-text="倒计时x秒"
          @end="end"
          @start="start"
          ref="uCode"
          @change="codeChange"
        >
        </uv-verification-code>
        <button class="login-btn-code login-btn-a" :loading="subBtnLoading" @click="handleLogin">
          登录
        </button>

      </view>

    </view>

    <!--隐私政策-->
    <view class="login-card-read fx-row-b" >
      <button class="icon-btn-no fx-row-s" open-type="agreePrivacyAuthorization">
        <uv-checkbox-group v-model="noticeChecked" class="fx-row-c">
          <uv-checkbox size="38" v-model="isChecked" name="checked" shape="circle" :activeColor="color.colorTextA"></uv-checkbox>
        </uv-checkbox-group>
      </button>

<!--      <uv-checkbox-group v-model="noticeChecked" class="fx-row-c">
        <uv-checkbox size="38" v-model="isChecked" name="checked" shape="circle" :activeColor="color.colorC"></uv-checkbox>
      </uv-checkbox-group>-->
      <view>
        <text class="text-color-a" @click="">登录即代表同意</text>

        <text class="text-color-b" @tap.prevent="handlePrivacyContract">《闪创店家小程序隐私保护指引》</text>
        <text class="text-color-b" @tap.prevent="jump('/pagesSetting/mine/aboutDetail')">《服务条款》</text>
        <text class="text-color-a">并授权统一认证使用本机号码</text>
      </view>
    </view>

    <view class="login-card-outher fx-col-b">
      <!-- <view class="login-card-outher-title fx-row-b">
        <view class="login-card-outher-title-left"></view>
        <view class="login-card-outher-title-center">其他方式登录</view>
        <view class="login-card-outher-title-right"></view>
      </view> -->
<!--      <button class="btn" open-type="getUserInfo" @getuserinfo="handleWxAuthorizeLogin">
        <uv-icon size="40" name="weixin-circle-fill"></uv-icon>
      </button>-->

      <!-- <button class="login-card-outher-btn" @click="handleWxAuthorizeLogin">
        <uv-icon color="#059A05FF" size="55" name="weixin-circle-fill"></uv-icon>
      </button> -->
    </view>

    <uv-toast ref="loginToast"></uv-toast>
    <toast></toast>
  </view>

  <!-- #ifdef MP-WEIXIN -->

  <!-- #endif -->
</template>


<script setup>
import { reactive, ref} from "vue";
import { ossImage,jump } from '@/utils/index'
import { header,color } from '@/enums/constants';
import { onLoad } from "@dcloudio/uni-app";
import loginApi from "@/apis/login";
import { userStore } from "@/stores";
import qs from "qs";

const store = userStore();
const subBtnLoading = ref(false);
const isChecked = ref(false)
const loginToast = ref(null);

//登录类型
const isLoginType = ref(true);
const formData = reactive({
  phone:'',
  code:'',
  wxCode:''
})


// 查看隐私政策｜使用条款
const handlePrivacyContract = ()=>{
  jump('/pagesSetting/mine/privacy')
}
const handleAgreePrivacyAuthorization = (res)=>{
  console.log(res)
}



//切换登录类型
const changeLoginType = ()=>{
  formData.phone = '';
  formData.code = '';
  isLoginType.value = !isLoginType;
}

//未勾选点击触发事件
const agreementPrompt = ()=>{
  loginToast.value.show({
    title: '请您勾用户选协议',
    type:'warning',
    position:'top'
  })
}

//code验证码
const uCode = ref(null);
const tips = ref('获取验证码');
const handleSend = ()=>{
  if(formData?.phone){
    loginApi.getValidCode({phone:formData.phone}).then((res) => {
      console.log(res)
      if (res.code === "SUCCESS") {
        uCode.value.start();
        loginToast.value.show({
          title: '验证码已发送',
          type:'default',
          position:'top'
        })
      }
    }).catch(err=>{
      console.log(err)
    });
  }else{
    loginToast.value.show({
      title: '请输入手机号',
      type:'warning',
      position:'top'
    })
  }
}

const codeChange = (para)=>{
  tips.value = para;
}


//获取用户信息
const handleGetUserInfo = ()=>{
  let para = {userId:0}
  loginApi.getUserInfo(para).then(res=>{
    if(res.code == 'SUCCESS'){
      store.setUserInfo(res?.data);
      isUserInfoInit(res?.data);
    }
  })
  loginApi.getUserInfoExt(para).then(res=>{
    if(res.code == 'SUCCESS'){
      store.setUserInfoExt(res?.data)
    }
  })
}


//登录
// 登录成功之后的跳转地址
const loginSuccessRedirectUrl = ref("");
// 页面加载切换登录类型及进入方式
onLoad((options) => {
  loginSuccessRedirectUrl.value = options?.loginSuccessRedirectUrl;
});

const handleLogin = ()=>{
  if(isReadyLogin()){
    let para = {
      phoneNumber:formData.phone,
      validateCode:formData.code
    }
    subBtnLoading.value = true;
    loginApi.loginSms(para).then((res)=>{
      store.setToken(res?.data);
      handleGetUserInfo();
    }).finally(()=>{
      subBtnLoading.value = false;
    })
  }
}

//一键登录
const handleGetphonenumber = (e)=>{
  const laUnchOptions = uni.getEnterOptionsSync();
  const scene = decodeURIComponent(laUnchOptions.query.scene)
  const query = qs.parse(scene);
  subBtnLoading.value = true;
  const { code } = e.detail;
  console.log("phone code", code);
  if(code) {
    loginApi.loginPhone({code}).then(res=>{
      store.setToken(res?.data);
      handleGetUserInfo();
      loginApi.updateLoginSession({ code: query.code }).then((res) => {
        console.log(res);
      })
    }).finally(()=>{
      subBtnLoading.value = false;
    })

  }
}

//判断是否第一次登录或者信息不全，跳转编写资料页面
const isUserInfoInit = (info)=>{
  if(!info){return}
  if(!info.avatar || !info.nickname || !info.gender){
    uni.reLaunch({
      url:`/pages/mine/edit/editInit?loginSuccessRedirectUrl=${loginSuccessRedirectUrl.value}`,
    });
  }else{
    if (loginSuccessRedirectUrl.value) {
      uni.reLaunch({
        url: decodeURIComponent(loginSuccessRedirectUrl.value),
      });
    }else{
      uni.reLaunch({
        url:'/pages/play/index',
      });
    }
  }
}





const test = ()=>{
  let para = {code:formData.wxCode}
  console.log(para);
  loginApi.wxAuthorizeLogin(para).then(res=>{
    console.log(res)
  })
}

//微信授权登录
const handleWxAuthorizeLogin = (e)=>{
  //let userInfo = e.detail.userInfo;
  ///console.log(userInfo);
  return;
  uni.login({
    provider:"weixin",
    success:(res => {

      formData.wxCode = res.code;
      console.log(formData.wxCode);

      /*uni.getUserInfo({
        success(info_res) {
          console.log(info_res)
          uni.request({
            url:'http://localhost:8080/wxlogin',
            method:"POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data:{
              code : code,
              rawData : info_res.rawData
            },
            success(res) {
              if(res.data.status == 200){
                that.$store.commit('login',userInfo);
                // uni.setStorageSync("userInfo",userInfo);
                // uni.setStorageSync("skey", res.data.data);
              }else{
                console.log('服务器异常')
              }
            },
            fail(error) {
              console.log(error)
            }
          })
          uni.hideLoading()
          uni.navigateBack()
        }
      })*/

    })
  })
}


const isReadyLogin=()=>{
  let text = ['请您勾用户选协议','请您输入电话号码','请您输入验证码'];
  let index = undefined;
  if(!isChecked.value){
    index = 0;
  }
  if(!formData.phone){
    index = 1;
  }
  if(!formData.code){
    index = 2;
  }
  if(index === undefined){
    return true;
  }else{
    loginToast.value.show({
      title:text[index],
      type:'warning',
      position:'top'
    })
  }
}



// 未填数据时禁用登录按钮
/*const isCheckAgreement = computed(() => {
  let flag = false;
  flag = noticeChecked.value.includes("checked");

  return flag;
});*/
</script>

<style lang="scss" scoped>
@import "../src/static/styles/componets.scss";
.login-card {
  position: relative;
  width: 100%;
  height: 100%;
  padding-top: 60rpx;
  text-align: center;
  box-sizing: border-box;

  //logo
  &-head{
    height: 200rpx;
    width: 330rpx;
    background-size: contain;
    background-color: transparent;
    margin:0 auto;
  }

  &-desc{
    padding-bottom: 20rpx;
    @include main-text0;
  }

  //输入交互
  &-box{
    height: 400rpx;
    //background-color:rgba(0,0,0,.2);
    @include main-line5;
    //初始登录
    &-a{}
    //一键登录
    &-b{
      &-list{
        //border-radius: 10rpx;
        //background-color: rgb(222, 222, 222,.3);
        margin-bottom: 30rpx;
        border-bottom:.5px solid $main-text-c;
      }
      .login-input{
        font-weight: 500;
        &-icon{
          padding:0 20rpx;
          color:$main-text-b;
        }
      }
      //验证码样式
      .login-code{
        color:$main-text-b;
      }
      //登录按钮
      .login-btn-code{
        margin-top: 100rpx;
      }
    }


    //显示手机号
    .login-phone{
      @include main-text2;
      height: 140rpx;
      color:$main-c;
    }
    .login-btn-a,.login-btn-b{
      padding:0 20rpx;
      line-height: 2.556;
      border-radius: 15rpx;
    }
    .login-btn-a{
      background-color:#303030;
      color:#fff;
      &:after{border:none;}
    }
    .login-btn-b{
      background-color:transparent;
      color:$main-text-a;
      &:after{border-radius:30rpx;border:1px solid $main-text-a;}
    }
  }

  //勾选协议
  &-read{
    margin-top:30rpx;
    flex-wrap: nowrap;
    text-align: left;
    line-height: 1;
    padding:0 10rpx;
    .text-color-a,.text-color-b{@include main-text5;}
    .text-color-a{color:$main-text-a;}
    .text-color-b{color:$main-b}
    &:deep(.u-checkbox__label){
      margin-right: 0;
    }
    .icon-btn-no{
      width: 90rpx;
    }
    &:deep(.button-hover){
      background-color: transparent !important;
    }
  }

  //其他登录
  &-outher{
    position: absolute;
    bottom:10rpx;
    width: 100%;
    height: 130rpx;
    @include main-text4;
    color:$main-text-b;
    &-title{
      width: 100%;
      &-left,&-right{width: 30%;height:.5rpx;background-color: $main-text-e;};
      &-center{
        width: 35%;
        line-height: 1.4;
        background-color:rgba(255,255,255,.6);
        @include main-text6;
        border-radius: 10rpx;
      }
    }
    &:deep(button){
      background-color: transparent;
      &:after{border: none}
      line-height: 1;
    }
  }

}

</style>
